package com.homedo.async.mysql.support.prepare.util;

import com.google.common.collect.Maps;
import com.homedo.async.mysql.support.meta.EntityMetaData;
import com.homedo.plainly.logger.Logger;
import com.homedo.plainly.logger.LoggerFactory;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author jgshun
 * @date 2020/3/5 2:59 PM
 */
public abstract class CollectRecordColumnValUtil {
    private static final Logger _LOGGER = LoggerFactory.getLogger(CollectRecordColumnValUtil.class);

    public static <T> Map<String, Object> collect(T record, EntityMetaData<T> entityMetaData, boolean includeNullVals) {
        Map<String, Object> columnValMap = Maps.newHashMap();

        Map<Field, String> fieldColumNameMapping = entityMetaData.getFieldColumNameMapping();

        fieldColumNameMapping.entrySet().forEach(e -> {
            e.getKey().setAccessible(true);
            try {
                Object val = e.getKey().get(record);
                if (val != null || (val == null && includeNullVals)) {

                    columnValMap.put(entityMetaData.getColumnNameConvertorMapping().get(e.getValue()).convertor(e.getValue(), e.getKey().getType())
                            , entityMetaData.getColumnValConvertorMapping().get(e.getValue()).convertor(val));
                }
            } catch (IllegalAccessException ex) {
                _LOGGER.error("[这里出现了错误，需要详细排查原因。{}]", ex.getMessage(), ex);
            }
        });

        return columnValMap;
    }

}
